var app = {
    openId: GetRequest()['openid'],
    prize: {
        tip: [],
        rewards: []
    },
    list: [],
    tList: [],
    init: function() {
        this.getPrizeList();
        this.closePanel();
        this.gamestart();
        this.bindCheck();
    },
    timerClock: function(leaveTime) {
        var context = this;
        var time = 1000;
        function leftMuniteAndSecend(leftTime) {
            // var days = parseInt(leftTime / 60 / 60 / 24, 10); 计算剩余的天数
            var hours = parseInt(leftTime / 60 / 60 % 24, 10); //计算剩余的小时
            var minutes = parseInt(leftTime / 60 % 60, 10); //计算剩余的分钟
            var seconds = parseInt(leftTime % 60, 10); //计算剩余的秒数
            minutes = checkTime(minutes);
            seconds = checkTime(seconds);
            return minutes + ":" + seconds;
        }
        function checkTime(i) { //将0-9的数字前面加上0，例1变为01
            if (i < 10) {
                i = "0" + i;
            }
            return i;
        }

        //显示倒数秒数
        function showTime() {
            leaveTime -= 1;
            var timer;
            $('#leaveTimeShow').html(leftMuniteAndSecend(leaveTime));
            if (leaveTime == 0) {
                $(".couten").remove();
                autoshowBar('.time');
                context.sendList();
                return;
            }
            clearTimeout(timer);
            timer = null;
            //每秒执行一次,showTime()
            timer = setTimeout(showTime, 1000);
        }
        //执行showTime()
        showTime();
    },
    //提交信息给后台
    sendList: function() {
        var context = this;
        var sendPrizeList = [];
        $.each(context.list, function(index, val) {
            if (val.type) {
                sendPrizeList.push(val);

            }
        });
        context.tList = context.tList.concat(sendPrizeList);
        console.log('7788', context.tList);
        $.ajax({
            type: 'post',
            url: 'http://10.122.202.211:8080/HD-newyear/newyear/receivePrize.action',
            dataType: 'jsonp',
            jsonp: 'callback',
            data: {
                param: JSON.stringify(context.tList),
                openid: app['openId']
            },
            success: function() {
                context = null;
                $('#seewhatBtn').click(function() {
                    location.href = './prize.html';
                })
            },
            error: function() {}
        })
    },
    rulerPanel: function() {
        //显示规则
         autoshowBar('.game');
    },
    //关闭按钮
    closePanel: function() {
        closeBar('#timeBtn', '.addr');
        closeBar('#followBtn', '.follow');
        closeBar('#bindphoneBtn', '.bindphone');
        closeBar('#rulerBtn', '.followflow');

    },
    //获取奖品列表
    getPrizeList: function() {
        var context = this;
        $.ajax({
            tyle: 'post',
            url: 'http://10.122.202.211:8080/HD-newyear/newyear/getPrizeList.action',
            data: {},
            dataType: "jsonp",
            jsonp: "callback",
            beforeSend: function() {
                //判断openId传过来了没有
                if (!Boolean(app['openId'])) {
                    alert('获取openId失败');
                }
            },
            success: function(response) {
                if (0 == response.code) {
                    //显示文字
                    if (Boolean(response.data)) {
                        $.each(response.data, function(index, val) {
                            if (!val.type) {
                                context.prize.tip.push(val);
                                context.tList.push(val);
                            } else {
                                context.prize.rewards.push(val);
                            }
                        })

                        console.log(context.tagList);
                    }

                }
            },
            error: function() {}
        });
    },
    //判断绑定公众号
    bindCheck: function() {
        var context = this;
        context.user = judgeFocuse(app['openId']);
        console.log('111111',context.user.bindPhoneStatus);
            var timer = setInterval(function() {
                    if(context.user.subscribe){
                        context.rulerPanel();
                    }
            }, 200);

    },
    //开始游戏按钮绑定
    gamestart: function() {
        var context = this;
        $('#gamestartbtn').on('click', function() {
            console.log('start');
            context.gameInit();
            autocloseBar('.game');
        })
    },
    //判断是否中奖
    showTag: function(tagList) {
        var context = this;
        console.log('type', tagList);
        if (!tagList || !tagList.length) {
            return '';
        }

        var index = Math.floor(Math.random() * (tagList.length));
        var singeTag = tagList.splice(index, 1);
        switch (singeTag[0].type) {
            case 0:
                if (0.5 < Math.random()) {
                    tagList = tagList.concat(singeTag);
                    return '神秘标签';
                }
                break;
            case 1:
                if (0.3 < Math.random()) {
                    tagList = tagList.concat(singeTag);
                    return '';
                }
                break;
            case 2:
                if (0.5 < Math.random()) {
                    tagList = tagList.concat(singeTag);
                    return '获得神秘标签';
                }
                break;
            case 3:
                if (0.5 < Math.random()) {
                    tagList = tagList.concat(singeTag);
                    return '';
                }
                break;
            case 4:
                if (0.5 < Math.random()) {
                    tagList = tagList.concat(singeTag);
                    return '';
                }
                break;
        }

        context.list.push(singeTag[0]);
        console.log(context.list);
        return singeTag[0].name;
    },
    randomGift: function(_this, maspi) {
        var context = this;
        if (Math.random() > 0.998) {
            console.log("hhh");
            context.getGift(_this, maspi, context.prize.rewards);
            return;
        } else if (Math.random() > 0.75) {
            context.getGift(_this, maspi, context.prize.tip);
        } else {
            context.getGift(_this, maspi, null);
        }
    },
    getGift: function(_this, maspi, tip) {
        var context = this;
        // 定义点击球伯乐的逻辑
        var ballonBrokenList = ['', 2, 2, 1, 1];
        var brokenindex = $(_this).find('a>img').attr('data-num');
        $(_this).stop().find('a>img').attr('src', "./images/news/broken_" + ballonBrokenList[brokenindex] + ".png");
        var timer1 = setTimeout(function() {
            clearTimeout(timer1);
            timer1 = null;
            $(_this).remove();
        }, 1000);
        //显示标签
        //显示标签
        //显示标签
        //显示标签
        $('body').append("<a  href='javascript:void(0);' class='active lemiao active_" + maspi + "'>" + context.showTag(tip) + "</a>");

        $('.active_' + maspi).css({"left": $(_this).offset().left, "top": $(_this).offset().top});
        $('.active_').show();
        $('.active_').addClass('animated zoomIn');
        var timer2 = setTimeout(function() {
            clearTimeout(timer2);
            timer2 = null;
            $('.active_' + maspi).fadeOut();
        }, 1500);

    },
    gameInit: function() {
        var context = this;
        var n = 0; //计时器
        var n_click = 1; //发送ajax的判断3的倍数发送减小交互压力
        var win = (parseInt($(".couten").css("width"))) - 80;
        $(".couten").css("height", $(document).height());
        $(".backward").css("height", $(document).height());
        var add = function() { //增加红包的数量
            var obj = new Object();
            var hb = parseInt(Math.random() * 4 + 1); //向下取整
            var Wh = parseInt(Math.random() * 60 + 40);
            var Left = parseInt(Math.random() * win);
            var rot = (parseInt(Math.random() * 10)) + "deg";
            var onoff = function() {
                onoff = Math.random();
                if (onoff < 0.5) {
                    return "-";
                } else {
                    return "+";
                }
            };
            var onoffnum = onoff();
            num++;
            $(".couten").append("<li class='li" + num + "' ><a href='javascript:;'><img  data-num='" + hb + "'  src='./images/news/balloon_" + hb + ".png'></a></li>");
            $(".li" + num).css({"left": Left});
            $(".li" + num + " a img").css({
                "width": Wh,
                "transform": "rotate(" + onoffnum + rot + ")",
                "-webkit-transform": "rotate(" + onoffnum + rot + ")",
                "-ms-transform": "rotate(" + onoffnum + rot + ")",
                /* Internet Explorer */
                "-moz-transform": "rotate(" + onoffnum + rot + ")",
                /* Firefox */
                "-webkit-transform": "rotate(" + onoffnum + rot + ")",
                /* Safari 和 Chrome */
                "-o-transform": "rotate(" + onoffnum + rot + ")"/* Opera */
            });
            $(".li" + num).addClass('liactive');
            $(".li" + num).on("webkitAnimationEnd", function() {
                $(this).remove();
            });

            //点击红包的时候弹出模态层
            $(".li" + num).one('click', function() {
                $(this).css({'pointer-events': 'none'});
                var _this = this; //保留this指向
                var maspi = num; //保留num数值
                n_click += 1;
                context.randomGift(_this, maspi);

            });
            //释放js内存
            hb = Wh = Left = rot = onoff = onoffnum = changeMath = chanyunxing = null;
            n++;
            if (n <= 300) {
                setTimeout(add, 1000); //控制红包数量
            } else {
                console.log('结束了');
            }
        }; //add结束
        //增加红包
        var num = 0;
        setTimeout(add, 3000);

        //游戏倒计时
        var backward = function() {
            numz--;
            if (numz > 0) {
                console.log(numz);
                $(".backward span").text(numz);
            } else {
                //游戏时间用完
                var leaveTime = parseInt(30000 / 1000);
                context.timerClock(leaveTime);

                $(".backward").remove();
                return;
            }
            setTimeout(backward, 1000);
        }
        //倒计时开始
        var numz = 4;
        backward();
        $(document).on('touchmove', function() {
            return false;
        });

        // 更换class不同奖品
        changeMath = null;

        function sendAjax(_this, maspi) {
            var sendto = $.ajax({
                url: "./json/data" + Math.floor(Math.random() * 2) + ".json?b=" + Math.random(),
                dataType: "json",
                timeout: 1000,
                data: {
                    "type": "1"
                },
                beforeSend: function() {},
                success: function(data) {
                    console.log("发送成功了");
                    $('body').append("<span class='active active" + maspi + "'></span>");
                    $('.active' + maspi).css({"left": $(_this).offset().left, "top": $(_this).offset().top});
                    // 定义点击球伯乐的逻辑
                    var ballonBrokenList = ['', 2, 2, 1, 1];
                    var brokenindex = $(_this).find('a>img').attr('data-num');
                    $(_this).stop().find('a>img').attr('src', "./images/news/broken_" + ballonBrokenList[brokenindex] + ".png");
                    setTimeout(function() {
                        $(_this).remove();
                    }, 1000);
                    $('.active' + maspi).show();
                    $('.active' + maspi).addClass('animated zoomIn');
                    setTimeout(function() {
                        $('.active' + maspi).remove();
                    }, 1000);

                    $('body').prepend("<strong class=" + changeClass() + "></strong>");
                },
                error: function() {}

            });
        }
    }
}
app.init();
